package com.ruoyi.framework.filter;


import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.springframework.stereotype.Component;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Component
public class DruidAdFilter implements Filter {

    // 监控页面的访问路径（与 druid.stat-view-servlet.url-pattern 一致）
    private static final String DRUID_URL_PATTERN = "/druid/";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (req.getRequestURI().startsWith(DRUID_URL_PATTERN)){
            CharResponseWrapper wrapper = new CharResponseWrapper(resp);
            chain.doFilter(request, wrapper);

            // 读取响应内容，删除广告相关代码
            String html = wrapper.toString();
            html = html.replaceAll("English","英文");
            html = html.replaceAll(".footer \\{", ".footer { display: none;");

            // 将处理后的 HTML 写回响应
            resp.setContentLength(html.getBytes(StandardCharsets.UTF_8).length);
            PrintWriter out = resp.getWriter();
            out.write(html);
            out.flush();
        }
       else {
            // 非 Druid 请求，直接放行
            chain.doFilter(request, response);
        }
    }

    /**
     * 包装响应对象，捕获输出流内容
     */
    private static class CharResponseWrapper extends HttpServletResponseWrapper {
        private final CharArrayWriter buffer;
        private final PrintWriter writer;

        public CharResponseWrapper(HttpServletResponse response) {
            super(response);
            this.buffer = new CharArrayWriter();
            this.writer = new PrintWriter(buffer, true);
        }

        @Override
        public PrintWriter getWriter() {
            return writer;
        }

        @Override
        public String toString() {
            return buffer.toString();
        }
    }
}
